package com.yonyou.lxp.account.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.yonyou.lxp.account.BaseTwoActivity;
import com.yonyou.lxp.account.R;
import com.yonyou.lxp.account.db.DbHelper;
import com.yonyou.lxp.account.entity.ExpenditureInfo;
import com.yonyou.lxp.account.entity.TypeInfo;
import com.yonyou.lxp.account.utils.Constants;
import com.yonyou.lxp.account.utils.DialogUtils;
import com.yonyou.lxp.account.utils.Tools;
import com.yonyou.lxp.account.views.time.SlideDateTimeListener;
import com.yonyou.lxp.account.views.time.SlideDateTimePicker;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.drakeet.materialdialog.MaterialDialog;

@ContentView(R.layout.activity_spending)
public class SpendingActivity extends BaseTwoActivity {


    @ViewInject(R.id.edt_spendingMoney)
    private EditText edt_spendingMoney;

    @ViewInject(R.id.edt_spendingRemarks)
    private EditText edt_spendingRemarks;

    @ViewInject(R.id.tv_spendingtime)
    private TextView tv_spendingtime;

    @ViewInject(R.id.spinner_spendingName)
    private Spinner spinner_spendingName;

    private List<TypeInfo> list_type = new ArrayList();
    private ArrayAdapter<TypeInfo> adapter;

    private DbManager db;
    private ExpenditureInfo expenditureInfo = new ExpenditureInfo();
    private MaterialDialog dialog;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        db = x.getDb(DbHelper.getDaoConfig());
        intent = getIntent();
        initDialog();
        init();
        getData();
    }

    /**
     * 组件初始化
     */
    private void init() {
        edt_spendingMoney.addTextChangedListener(textWatcher);
        adapter = new ArrayAdapter<TypeInfo>(mContext, android.R.layout.simple_list_item_1, list_type);
        spinner_spendingName.setAdapter(adapter);
        spinner_spendingName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                expenditureInfo.setT_id(list_type.get(position).getT_id());
                expenditureInfo.setT_name(list_type.get(position).getT_name());
                expenditureInfo.setT_type(list_type.get(position).getT_type());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }


    /**
     * 初始化Dialog弹框 输入项目名称
     */
    private void initDialog() {
        dialog = DialogUtils.getDailog(mContext);
        dialog.setTitle("设置项目名称：");
        final EditText edt = new EditText(mContext);
        dialog.setContentView(edt);
        dialog.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String t_type = (edt.getText() + "").trim();
                if (t_type.length() != 0) {
                    TypeInfo typeInfo = new TypeInfo();
                    typeInfo.setT_name(t_type);
                    typeInfo.setT_type("0");
                    try {
                        db.saveOrUpdate(typeInfo);
                        dialog.dismiss();
                        getData();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                } else {
                    Tools.showToast(mContext, "项目名不能为空");
                }
            }
        });

        dialog.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 获取数据
     */
    private void getData() {
        x.task().post(new Runnable() {
            @Override
            public void run() {
                try {
                    list_type.clear();
                    adapter.notifyDataSetChanged();

                    List data = (List<TypeInfo>) (db.selector(TypeInfo.class).where("t_type", "=", "0").findAll());

                    if (data != null) {
                        list_type.addAll(data);
                    } else {
                        dialog.show();
                    }
                    spinner_spendingName.setSelection(list_type.size() - 1);

                    expenditureInfo = intent.getParcelableExtra("infoData");
                    if (expenditureInfo != null) {
                        edt_spendingMoney.setText(expenditureInfo.getE_money());
                        tv_spendingtime.setText(Constants.mFormatter.format(expenditureInfo.getE_time()));
                        edt_spendingRemarks.setText(expenditureInfo.getE_remarks());
                        int _index = -1;
                        TypeInfo typeInfo;
                        for (int i = 0; i < list_type.size(); i++) {
                            typeInfo = list_type.get(i);
                            if (typeInfo.getT_id() == expenditureInfo.getT_id() && typeInfo.getT_name().equals(expenditureInfo.getT_name())) {
                                _index = i;
                                break;
                            }
                        }
                        if (_index != -1) {
                            spinner_spendingName.setSelection(_index);
                        }
                    } else {
                        expenditureInfo = new ExpenditureInfo();
                    }

                    adapter.notifyDataSetChanged();
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        });

    }


    @Event(value = {R.id.tv_spendingtime, R.id.btn_save, R.id.img_add})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_spendingtime://时间选择
                new SlideDateTimePicker.Builder(getSupportFragmentManager())
                        .setListener(listener)
                        .setInitialDate(new Date())
                        .setMaxDate(new Date())
                        //.setIs24HourTime(true)
                        //.setTheme(SlideDateTimePicker.HOLO_DARK)
                        //.setIndicatorColor(Color.parseColor("#990000"))
                        .build()
                        .show();

                break;
            case R.id.img_add://新加项目名称
                dialog.show();
                break;
            case R.id.btn_save://保存
                if (check()) {
                    try {
                        db.saveOrUpdate(expenditureInfo);
                        Tools.showToast(mContext, "保存成功");
                        Intent it = new Intent();
                        it.putExtra("infoData", expenditureInfo);
                        setResult(10002, it);
                        finish();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    break;
                }
        }
    }

    /**
     * 检查数据正确性
     *
     * @return
     */
    private boolean check() {
        String money = (edt_spendingMoney.getText() + "").trim();
        if (money.length() != 0) {
            expenditureInfo.setE_money(money);
        } else {
            Tools.showToast(mContext, "请输入金额");
            return false;
        }

        String time = tv_spendingtime.getText() + "";
        if (time.length() == 0) {
            Tools.showToast(mContext, "请选择时间");
            return false;
        }

        if ("暂无项目".equals(((TypeInfo) (spinner_spendingName.getSelectedItem())).getT_name())) {
            Tools.showToast(mContext, "请选择收入项目");
            return false;
        }

        expenditureInfo.setE_remarks((edt_spendingRemarks.getText() + "").trim());

        return true;
    }

    /**
     * 设置小数位数控制
     */

    TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            if (s.toString().contains(".")) {
                if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                    s = s.toString().subSequence(0,
                            s.toString().indexOf(".") + 3);
                    edt_spendingMoney.setText(s);
                    edt_spendingMoney.setSelection(s.length());
                }
            }
            if (s.toString().trim().substring(0).equals(".")) {
                s = "0" + s;
                edt_spendingMoney.setText(s);
                edt_spendingMoney.setSelection(2);
            }

            if (s.toString().startsWith("0")
                    && s.toString().trim().length() > 1) {
                if (!s.toString().substring(1, 2).equals(".")) {
                    edt_spendingMoney.setText(s.subSequence(0, 1));
                    edt_spendingMoney.setSelection(1);
                    return;
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }

    };

    /**
     * 时间选择器
     */
    private SlideDateTimeListener listener = new SlideDateTimeListener() {

        @Override
        public void onDateTimeSet(Date date) {
            String time = Constants.mFormatter.format(date);
            tv_spendingtime.setText(time);
            expenditureInfo.setE_time(date.getTime());
        }

//        // Optional cancel listener
//        @Override
//        public void onDateTimeCancel()
//        {
//            Toast.makeText(mContext, "Canceled", Toast.LENGTH_SHORT).show();
//        }
    };


}
